/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bimager.jtwain;


import com.bimager.config.Config;
import com.bimager.jtwain.ui.LoadingPopup;
import com.sun.jmx.snmp.tasks.Task;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dialog;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BandedSampleModel;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.RGBImageFilter;
import java.awt.image.Raster;
import java.awt.image.SampleModel;
import java.awt.image.WritableRaster;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.InputMap;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.KeyStroke;
import javax.swing.ProgressMonitor;
import javax.swing.SwingWorker;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import sun.awt.image.WritableRasterNative;
import sun.net.www.protocol.http.HttpURLConnection;

/**
 *
 * @author Amskape
 */
public class JTwainApplet extends javax.swing.JApplet implements PropertyChangeListener{
    
 jtwain jt ;
 private String filename;
 String product;
 ImageCanvas imageCanvas ;
 //ImageCanvas canvas ;
 File currentFile;
 File tempFile;
 String  uploadurl;
 int patID;
 int[] pixels; 
 File ImageDir;  
 JFrame infopopup;
      ImageIcon closeTab = new ImageIcon(JTwainApplet.class.getResource("images/closeTab.png"));
      ImageIcon image_edit = new ImageIcon(JTwainApplet.class.getResource("images/image_edit.png"));
   
    /**
     * Initializes the applet JTwainApplet
     */
      Properties config =new Properties();
      String os=System.getProperty("os.name");
      String arch=System.getProperty("os.arch");
      boolean applicationSupport= false;
    @Override
    public void init() {
        
                    File baseDir = new File(System.getProperty("java.io.tmpdir"));
                    String tempfoldername= "imagesbimagertwain";
                  
                   File dir = new File(baseDir,tempfoldername) ;
                   System.out.println(dir.getAbsolutePath());
                   if(!dir.exists())
                   {  dir.mkdir();
                      
                   }
                 
                    if(dir.exists())
                   { 
                      ImageDir = dir;
                   }
                   
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JTwainApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JTwainApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JTwainApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JTwainApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
           // JTwainApplet.class.getResource("images/closeTab.png");
             try{      
               config.load( Config.class.getResourceAsStream("config.properties"));
             }catch(IOException ex)
             {
                 
                 
                 
             }
              String[] supportos = config.getProperty("support.os").split(",");
              String[] supportosarch = config.getProperty("support.os.arch").split(",");
            
             
              for (String string : supportos) {
                     if(string.matches(os)){
                        applicationSupport = true;
                         
                     }
                 }
             
             
             
           //  if(os)
           
           
            if(applicationSupport){
               //  System.out.println(os+"\n");
           // System.out.println(arch);
                   jt = new jtwain();
            }
            
           uploadurl = getParameter("uploadURL"); 
           if(uploadurl == null||uploadurl == "")
           {
               uploadurl=config.getProperty("default.uploadURL");
               
           }
           patID = 0;
           if(getParameter("patId") != null)
             patID     = Integer.parseInt(getParameter("patId"));
           else
               patID = Integer.parseInt(config.getProperty("default.patientId"));
        /* Create and display the applet */
        try {
            java.awt.EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                   
                     initGUI();
                      
                }
            });
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void start() {
        super.start(); //To change body of generated methods, choose Tools | Templates.
          if(applicationSupport){
        String [] sources = jt.getSourceList();
        for (String string : sources) {
             if(string!= null)
                  sourcelist.addItem(string);
                       }
                       /* for (String s : sources) {
                        * sourcelist.addItem(s);
                        * // System.out.println(s);
                        * }*/
        if( sources.length >0){
           sourcelist.setEnabled(true);
           btnScan.setEnabled(true);
           btnScan.setVisible(true);
                     
                   }
          }else
          {
              
              JOptionPane.showMessageDialog(this, "Operating System not Supporting", "Compatabilty Error", JOptionPane.ERROR_MESSAGE);
             this.setEnabled(false);
             this.setVisible(false);
          }
    
    }

    @Override
    public void destroy() { 
        super.destroy(); //To change body of generated methods, choose Tools | Templates.
     
       
    }

    @Override
    public void stop() {
        super.stop(); //To change body of generated methods, choose Tools | Templates.
    }
    

    /**
     * This method is called from within the init() method to initialize the
     * form. WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    private javax.swing.JButton btnsaveOnly;
    private javax.swing.JButton btnCrop;
    private javax.swing.JButton btnFlip;
    private javax.swing.JButton btnFlipV;
    private javax.swing.JButton btnResize;
    private javax.swing.JButton btnSave;
    private javax.swing.JButton btnScan;
    private javax.swing.JButton btnrotateleft;
    private javax.swing.JButton btnrotatergt;
     private javax.swing.JButton btnInfo;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jsp;
    private javax.swing.JLabel scaleLblH;
    private javax.swing.JLabel scaleLblW;
    private javax.swing.JComboBox sourcelist;
    private javax.swing.JTextField txtscaleH;
    private javax.swing.JTextField txtscaleW;
    private javax.swing.JProgressBar saveProgress;
    private javax.swing.JLabel statusLbl;
    private javax.swing.JTextField txtFileName;
    private javax.swing.JSeparator sep1;
    private javax.swing.JButton refresh;
    private javax.swing.JTabbedPane imageTabs;
    private javax.swing.ProgressMonitor taskprogress;

    
    @SuppressWarnings("unchecked")
    
    private  void initGUI()
    {
        
        
        jPanel1 = new javax.swing.JPanel();
        sourcelist = new javax.swing.JComboBox();
        btnScan = new javax.swing.JButton();
        jsp = new javax.swing.JScrollPane();
        ImageIcon RRicon = new ImageIcon(JTwainApplet.class.getResource("images/RR32.png"));
        ImageIcon RLicon = new ImageIcon(JTwainApplet.class.getResource("images/RL32.png"));
        ImageIcon FlipHicon = new ImageIcon(JTwainApplet.class.getResource("images/FH32.png"));
        ImageIcon FlipVicon = new ImageIcon(JTwainApplet.class.getResource("images/FV32.png"));
        ImageIcon cropicon = new ImageIcon(JTwainApplet.class.getResource("images/crop32.png"));
        ImageIcon scaleicon = new ImageIcon(JTwainApplet.class.getResource("images/resize32.png"));
        ImageIcon refreshicon = new ImageIcon(JTwainApplet.class.getResource("images/refresh32.png"));
      
        btnrotatergt = new javax.swing.JButton(RRicon);
        btnrotateleft = new javax.swing.JButton(RLicon);
        btnSave = new javax.swing.JButton();
        btnCrop = new javax.swing.JButton(cropicon);
        btnFlip = new javax.swing.JButton(FlipHicon);
        txtscaleW = new javax.swing.JTextField();
        txtscaleH = new javax.swing.JTextField();
        scaleLblW = new javax.swing.JLabel();
        scaleLblH = new javax.swing.JLabel();
        btnResize = new javax.swing.JButton(scaleicon);
        saveProgress = new javax.swing.JProgressBar(0,100);
        saveProgress.setVisible(false);
        saveProgress.setStringPainted(true);
        btnFlipV = new javax.swing.JButton(FlipVicon);
        sep1 = new javax.swing.JSeparator();
        statusLbl = new javax.swing.JLabel();
        txtFileName = new javax.swing.JTextField();
        btnsaveOnly = new javax.swing.JButton();
        refresh = new javax.swing.JButton();
        imageTabs = new javax.swing.JTabbedPane();
        btnInfo = new javax.swing.JButton();
        sourcelist.setEnabled(false);
      
        sourcelist.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sourcelistActionPerformed(evt);
            }
        });

        btnScan.setText("Scan");
        btnScan.setEnabled(false);
        btnScan.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                try {
                    try {
                        btnScanActionPerformed(evt);
                    } catch (IOException ex) {
                        Logger.getLogger(JTwainApplet.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } catch (URISyntaxException ex) {
                    Logger.getLogger(JTwainApplet.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

       // btnrotatergt.setText("Rotate Right");
        btnrotatergt. setEnabled(false);
        btnrotatergt.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        btnrotatergt.setContentAreaFilled(false);
        
        btnrotatergt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnrotatergtActionPerformed(evt);
            }
        });

       // btnrotateleft.setText("Rotate Left");
        btnrotateleft.setEnabled(false);
         btnrotateleft.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        btnrotateleft.setContentAreaFilled(false);
        btnrotateleft.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
              btnrotateleftActionPerformed(evt);
            }
        });

        btnSave.setText("Start Upload");
        btnSave.setEnabled(false);
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

       // btnCrop.setText("Crop");
        btnCrop.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        btnCrop.setContentAreaFilled(false);
        btnCrop.setEnabled(false);
        btnCrop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
               btnCropActionPerformed(evt);
            }
        });

      //  btnFlip.setText("");
        btnFlip.setEnabled(false);
        btnFlip.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        btnFlip.setContentAreaFilled(false);
        btnFlip.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFlipActionPerformed(evt);
            }
        });

        txtscaleW.setToolTipText("Width of Image to Scale");
        txtscaleW.setEnabled(false);

        txtscaleH.setToolTipText("Height of Image to Scale");
        txtscaleH.setEnabled(false);

        scaleLblW.setText("W");
        scaleLblW.setToolTipText("Width of Image to Scale");

        scaleLblH.setText("H");
        scaleLblH.setToolTipText("Height of Image to Scale");

        btnResize.setText("Resize");
        btnResize.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        btnResize.setContentAreaFilled(false);
        btnResize.setEnabled(false);
        btnResize.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnResizeActionPerformed(evt);
            }
        });
          saveProgress.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                saveProgressPropertyChange(evt);
            }
        });
       // btnFlipV.setText("");
        btnFlipV.setPreferredSize(new java.awt.Dimension(32, 32));
        btnFlipV.setEnabled(false); 
        btnFlipV.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        btnFlipV.setContentAreaFilled(false);
         btnFlipV.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFlipVActionPerformed(evt);
            }
        });
        
        
        txtFileName.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        txtFileName.setEnabled(false);
        btnsaveOnly.setText("Save");
         btnsaveOnly.setEnabled(false);
        btnsaveOnly.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnsaveOnlyActionPerformed(evt);
            }
        });
        refresh.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        refresh.setContentAreaFilled(false);
        refresh.setPreferredSize(new java.awt.Dimension(32, 32));
        refresh.setIcon(refreshicon);
        refresh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                refreshActionPerformed(evt);
            }
        });
        imageTabs.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                imageTabsStateChanged(evt);
            }
        });
         btnInfo.setText("Info");
        btnInfo.setToolTipText("Show Image Informations");
        btnInfo.setName(""); // NOI18N
        btnInfo.setPreferredSize(new java.awt.Dimension(72, 32));
        btnInfo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnInfoActionPerformed(evt);
            }
        });
         btnInfo.setEnabled(false);
        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(txtFileName, javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(btnrotateleft, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnrotatergt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnCrop, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnFlip, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnFlipV, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(scaleLblW)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtscaleW, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(scaleLblH)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txtscaleH, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnResize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnInfo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(sep1, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(sourcelist, javax.swing.GroupLayout.PREFERRED_SIZE, 233, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(refresh, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(46, 46, 46)
                                .addComponent(btnScan, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnSave)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnsaveOnly)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(saveProgress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(statusLbl, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addComponent(imageTabs))
                        .addContainerGap())))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnScan)
                    .addComponent(btnSave)
                    .addComponent(sourcelist, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnsaveOnly)
                    .addComponent(refresh, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3)
                .addComponent(txtFileName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnrotateleft, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnrotatergt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnCrop, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnFlip, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnFlipV, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtscaleW, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(scaleLblW)
                    .addComponent(scaleLblH)
                    .addComponent(txtscaleH, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnResize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnInfo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(sep1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(imageTabs, javax.swing.GroupLayout.DEFAULT_SIZE, 392, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(saveProgress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(statusLbl))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
    }
    
    private void saveProgressPropertyChange(java.beans.PropertyChangeEvent evt) {                                            
        // TODO add your handling code here:
        
        
        
    }  
     private void btnScanActionPerformed(java.awt.event.ActionEvent evt) throws URISyntaxException, IOException {                                        
        // TODO add your handling code here:
         /*   URL imagurl = JTwainApplet.class.getResource("images/loading.gif");
          * Image loading = getImage(imagurl);
          * LoadingPopup lp = new LoadingPopup(loading);
          * lp.setVisible(true);
          * add(lp);
          * setComponentZOrder(lp, getComponentZOrder(imageCanvas)+1);
          * String host = getCodeBase().getHost();*/
                
        if(-1 == sourcelist.getSelectedIndex())
        return;

           setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
          try{
           URL uploadUrl = getCodeBase();
           URI uploaduri = uploadUrl.toURI();
           String Selectedsource =  (String)sourcelist.getSelectedItem();
           filename = "ScannedImage_"+Long.toString(System.currentTimeMillis())+".tif";
           
           File imageFolder = new File(ImageDir,filename);
           //String name = imageFolder.getAbsolutePath();
           //int i = imageFolder.getAbsolutePath().lastIndexOf(System.getProperty("file.separator"));
          // String path=     name.substring(0, i);
           //path.concat(System.getProperty("file.separator"));
         
        
           String[]  imName =  jt.aqcuireImage(Selectedsource,filename,ImageDir.getAbsolutePath()+System.getProperty("file.separator"));
            if (imName.length == 0 ){
                  setCursor(null); //turn off the wait cursor
                 // System.out.println("ERROR");
                 return ;
            }
           int total = imName.length;
      
       
          for (String image : imName) {
               System.out.println(ImageDir.getAbsolutePath());
              File imagefile = new File(ImageDir,image);
              //System.out.println(file.getAbsolutePath());
             PlanarImage scanedimage = JAI.create("fileload", imagefile.getAbsolutePath());
             ImageCanvas imageCanvas = new ImageCanvas(scanedimage,imagefile.getAbsolutePath(),imagefile);
             JScrollPane imagescroller = new JScrollPane(imageCanvas,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED , JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
           //  imageTabs.addTab(imagefile.getName(), imagescroller);
              imageTabs.addTab(null, imagescroller);
              int pos = imageTabs.indexOfComponent(imagescroller);

    // Create a FlowLayout that will space things 5px apart
                FlowLayout f = new FlowLayout(FlowLayout.CENTER, 5, 0);

                // Make a small JPanel with the layout and make it non-opaque
                          JPanel pnlTab = new JPanel(f);
                          pnlTab.setOpaque(false);

                // Add a JLabel with title and the left-side tab icon
                          JLabel lblTitle = new JLabel(imagefile.getName());
                          lblTitle.setIcon(image_edit);

                // Create a JButton for the close tab button
                JButton btnClose = new JButton();
                btnClose.setOpaque(false);

                // Configure icon and rollover icon for button
                btnClose.setRolloverIcon(closeTab);
                btnClose.setRolloverEnabled(true);
                btnClose.setIcon(closeTab);

                // Set border null so the button doesn't make the tab too big
                btnClose.setBorder(null);

                // Make sure the button can't get focus, otherwise it looks funny
                btnClose.setFocusable(false);
                btnClose.addActionListener(new ActionListener() {

                          @Override
                          public void actionPerformed(ActionEvent e) {
                           tabCloseAction(e);
                          }
                      });
                // Put the panel together
                pnlTab.add(lblTitle);
                pnlTab.add(btnClose);

                // Add a thin border to keep the image below the top edge of the tab
                // when the tab is selected
                pnlTab.setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));

                // Now assign the component for the tab
                imageTabs.setTabComponentAt(pos, pnlTab);

               // btnClose.addActionListener(listener);

                // Optionally bring the new tab to the front
                imageTabs.setSelectedComponent(imagescroller);

                
         }
                 btnInfo.setEnabled(true);
                 btnSave.setEnabled(true);
                 btnsaveOnly.setEnabled(true);
                 btnSave.setVisible(true);
                 btnrotatergt.setEnabled(true);
                 btnrotateleft.setEnabled(true);
                 btnFlipV.setEnabled(true);
                 btnFlip.setEnabled(true);
                 btnCrop.setEnabled(true);
                 txtscaleW.setEnabled(true);
                 txtscaleH.setEnabled(true);
                 btnResize.setEnabled(true);
          }catch(Exception ex)
          {
               System.out.println(ImageDir.getAbsolutePath());
              
               System.err.println("Exception -"+ex.getMessage());
            
               //  currentFile = new File(filename);
               //  txtFileName.setText(currentFile.getAbsolutePath());
                   setCursor(null); //turn off the wait cursor
          }
          
                 
                // currentFile = new File(filename);
                 //txtFileName.setText(currentFile.getAbsolutePath());
                   setCursor(null); //turn off the wait cursor
    }                                       

    private void sourcelistActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
      if ( sourcelist.getSelectedIndex() ==-1)
      {
          btnScan.setVisible(false);
         
      }
      else
      {
            
           btnScan.setVisible(true);
          
      }
    }                                          
    private  String boundary;
    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt)  {                                        
        // TODO add your handling code here:
        // String filename = "ScannedImage_"+new Date().getTime()+".tif";
        

           saveProgress.setVisible(true);
           saveProgress.setValue(0);
          //imageCanvas.saveImage(filename);
           btnSave.setEnabled(false);
           setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
          
           SaveAndUpload task  = new SaveAndUpload();
           task.addPropertyChangeListener(this);
           task.execute();
          
       
      
      // URL uploadUrl = getCodeBase(); 
       

    }                                       
   private void btnsaveOnlyActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
        
       
       
          //imageCanvas.saveImage(filename);
           btnSave.setEnabled(false);
           setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
          
           SaveTask task  = new SaveTask();
           //taskprogress = new ProgressMonitor(this, "Saving in progress.....", "",0,);
           task.addPropertyChangeListener(this);
           task.execute();
          
       //imageCanvas.saveImage(filename);
    } 
    private void btnrotatergtActionPerformed(java.awt.event.ActionEvent evt) {                                             
        // TODO add your handling code here:
     
      imageCanvas.rotateRight();
       
    
     
    }                                            

    private void btnrotateleftActionPerformed(java.awt.event.ActionEvent evt) {                                              
        // TODO add your handling code here:
      imageCanvas.rotateLeft();
     
    }                                             

    private void btnCropActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        
        
       imageCanvas.crop();
//        ia.crop();
        
        
        
    }                                       
  private void settingmenuActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
      JFrame pref = new  JFrame("Settings");
      
      pref.pack();
      pref.setVisible(true);
      
    } 
    private void btnFlipActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:

       imageCanvas.flipH();
 
       
    }                                       
private void btnFlipVActionPerformed(java.awt.event.ActionEvent evt) {                                         
       imageCanvas.flipV();
    }  
    private void btnResizeActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
        if(txtscaleH.getText() != null && txtscaleW.getText() !=null){
        int h   = Integer.parseInt(txtscaleH.getText()) ;
        int  w   = Integer.parseInt(txtscaleW.getText()) ;
        
        
       imageCanvas.scale(w, h);
       // if(h != null && w!= null)
        // ia.scaling(w,h);
     
        }
        
    } 
  private void btnInfoActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
      if(imageCanvas != null){
      
            infopopup = new JFrame("Image Info");
         
          infopopup.requestFocus();
      
      for (String i : imageCanvas.image.getPropertyNames()) {
        //  System.out.println(i);
      }
      //infopopup.removeAll();
      InfoPanel infopanel = new InfoPanel();
      infopanel.lblwidth.setText(Integer.toString(imageCanvas.getImagewidth()));
      infopanel.lblheight.setText(Integer.toString(imageCanvas.getImageheight() ));
      //infopanel.lblHR.setText();imageCanvas.image.getColorModel()
     // infopanel.lblVR.setText();
      infopanel.lblbd.setText(Integer.toString(imageCanvas.image.getColorModel().getPixelSize()));
       // popup.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        infopopup.add(infopanel);
        //JDialog dailog = new  JDialog(popup,true);
        //popup.setContentPane();
        //dailog.setOpaque(true); //content panes must be opaque
       // popup.setContentPane(dailog);

        //Display the window.
       infopopup.pack();
       
       infopopup.setVisible(true);
        
      }
      else
      {
          if(infopopup.isDisplayable())
           infopopup.dispose();
           
          
      }
         //add(popup);
        
    }      
     private void refreshActionPerformed(java.awt.event.ActionEvent evt) {   
         
                    sourcelist.setEnabled(false);
                    btnScan.setEnabled(false);
                    btnScan.setVisible(false);
          String [] sources = jt.getSourceList();
                    
                   sourcelist.removeAllItems();
                       for (String string : sources) {
                           if(string!= null)
                              sourcelist.addItem(string);
                       }
                       /* for (String s : sources) {
                        * sourcelist.addItem(s);
                        * // System.out.println(s);
                        * }*/
                      if( sources.length >0){
                    sourcelist.setEnabled(true);
                    btnScan.setEnabled(true);
                    btnScan.setVisible(true);
                     
                   }
        // TODO add your handling code here:
    }  
     private void imageTabsStateChanged(javax.swing.event.ChangeEvent evt) {                                       
        // TODO add your handling code here:
           JTabbedPane sourceTabbedPane = (JTabbedPane) evt.getSource();
               int index = sourceTabbedPane.getSelectedIndex();
               if(sourceTabbedPane.getTabCount() >0){
               JScrollPane pane = (JScrollPane) sourceTabbedPane.getComponentAt(index);
              
                imageCanvas = (ImageCanvas) pane.getViewport().getView();
                    btnSave.setEnabled(true);
                    btnsaveOnly.setEnabled(true);
                   // btnSave.setVisible(true);
                    btnrotatergt.setEnabled(true);
                    btnrotateleft.setEnabled(true);
                    btnFlipV.setEnabled(true);
                    btnFlip.setEnabled(true);
                    btnCrop.setEnabled(true);
                    txtscaleW.setEnabled(true);
                    txtscaleH.setEnabled(true);
                    btnResize.setEnabled(true);
                    btnInfo.setEnabled(true);
                    txtFileName.setText(imageCanvas.getImageFileName());
               }
               else
               {
           infopopup.dispose();            
        btnSave.setEnabled(false);
        btnInfo.setEnabled(false);
        btnsaveOnly.setEnabled(false);
       // btnSave.setVisible(true);
        btnrotatergt.setEnabled(false);
        btnrotateleft.setEnabled(false);
        btnFlipV.setEnabled(false);
        btnFlip.setEnabled(false);
        btnCrop.setEnabled(false);
        txtscaleW.setEnabled(false);
        txtscaleH.setEnabled(false);
        btnResize.setEnabled(false);
        imageCanvas = null;
        txtFileName.setText("");
               }
                   
    }
     private void  tabCloseAction(ActionEvent evt)
     {
         
         
         imageTabs.removeTabAt(imageTabs.getSelectedIndex());
         
         
     }
     
     
     
     
     
     
     
     //worker thread secion
      class SaveAndUpload extends SwingWorker<Boolean, Void>
    {
         String lineEnd = "\r\n"; 
         String twoHyphens = "--"; 
         String boundary =  "*****"; 
         int bytesRead, bytesAvailable, bufferSize;
         byte[] buffer; 
         int maxBufferSize = 1*1024*1024;
         URL connectioUrl;
         java.net.HttpURLConnection connection;
         String Url;
         File uploadinFile;
 
        @Override
        protected Boolean doInBackground() throws Exception {
            
            
                    setProgress(0);
                    int progress = 0;
                     
                    System.out.println(uploadurl);
                    connectioUrl = new URL(uploadurl);
                    
                    connection = (java.net.HttpURLConnection) connectioUrl.openConnection();
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                        
                    connection.setUseCaches(false); 
                    connection.setRequestMethod("POST");
                    connection.setRequestProperty("Connection", "Keep-Alive"); 
                    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary); 
                    uploadinFile = imageCanvas.getImageFile();
                    DataOutputStream dos=null; 
                    FileInputStream fileInputStream=null;
                    
            
                    try {
                              // Send a binary file
                        dos = new DataOutputStream( connection.getOutputStream() );
                                // Send parameter #1
                        dos.writeBytes(twoHyphens + boundary + lineEnd); 
                        dos.writeBytes("Content-Disposition: form-data; name=\"patientId\"" + lineEnd + lineEnd);
                        dos.writeBytes(patID + lineEnd);

                        // Send parameter #2
                        /*   dos.writeBytes(twoHyphens + boundary + lineEnd);
                         * dos.writeBytes("Content-Disposition: form-data; name=\"param2\"" + lineEnd + lineEnd);
                         * dos.writeBytes("foo2" + lineEnd);*/
                        
                        
                        dos.writeBytes(twoHyphens + boundary + lineEnd); 
                        dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + uploadinFile.getName() +"\"" + lineEnd); 
                        dos.writeBytes(lineEnd); 



                 // create a buffer of maximum size 
                        long writen;
                        
                        long totalsize = uploadinFile.length();
                        fileInputStream = new FileInputStream(uploadinFile);
                        bytesAvailable = fileInputStream.available(); 
                        
                        bufferSize = Math.min(bytesAvailable, maxBufferSize); 
                        buffer = new byte[bufferSize]; 
                        bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
                        
                      //  connection.getContentLength();
                        while (bytesRead > 0) 
                        { 
                          dos.write(buffer, 0, bufferSize); 
                          
                          writen = dos.size();
                          progress = (int)(writen/totalsize)*100;
                          setProgress(progress);
                        //  publish(progress);
                          bytesAvailable = fileInputStream.available(); 
                          bufferSize = Math.min(bytesAvailable, maxBufferSize); 
                          bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
                         } 
                         dos.writeBytes(lineEnd); 
                         dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 
                         fileInputStream.close(); 
                         dos.flush(); 
                         dos.close();
                    } catch (IOException ex) {
                        Logger.getLogger(UploadUtility.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    finally
                    {
                        if(fileInputStream != null)
                           fileInputStream.close(); 

                        if(dos !=null){
                         dos.flush(); 
                         dos.close();  
                        }

                    }
                    int status = connection.getResponseCode();
                    System.out.println(""+status);
                    PrintWriter  outputStream  = null;
                    outputStream  = new PrintWriter(new FileWriter("error.html"));
                    if (status == java.net.HttpURLConnection.HTTP_OK) {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                         String line = null;
                          while ((line = reader.readLine()) != null) {
                          outputStream.println(line);
                          
                          }
                         reader.close();
                        outputStream.close();
                         connection.disconnect();
                       return true;

                            } else {
                        return false;
                                    //throw new IOException("Server returned non-OK status: " + status);
                            } 
                    
                    
                    
                    
         
        }

        @Override
        protected void done() {
            super.done(); //To change body of generated methods, choose Tools | Templates.
            
            
            btnSave.setEnabled(true);
            saveProgress.setVisible(false);
            setCursor(null); //turn off the wait cursor
        }
        
        
        
    }
    
    
 //create Worker thread for save
    class SaveTask extends SwingWorker<Void, Void>
    {

        @Override
        protected Void doInBackground() throws Exception {
            
             Random random = new Random();
            setProgress(0);
          
        imageCanvas.saveImage(filename);
        setProgress(100);    
           return null;
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        protected void done() {
            super.done(); //To change body of generated methods, choose Tools | Templates.
            btnSave.setEnabled(true);
            saveProgress.setVisible(false);
            setCursor(null); //turn off the wait cursor
        }
        
        
    }
       @Override
    public void propertyChange(PropertyChangeEvent evt) {
       
        if ("progress" == evt.getPropertyName()) {
             System.out.println("prgress");
            int progress = (Integer) evt.getNewValue();
            saveProgress.setValue(progress);
          
        }
        
        
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

     
     
     class ScaningTask  extends SwingWorker<Boolean, Void>
     {

        @Override
        protected Boolean doInBackground() throws Exception {
            Random random = new Random();
            int scanprogress = 0;
            //Initialize progress property.
            setProgress(0);
          
           scanprogress = 5;
           setProgress(scanprogress);
       
         return true;
        }

        @Override
        protected void done() {
            super.done(); //To change body of generated methods, choose Tools | Templates.
            if(imageTabs.getTabCount() >0)
            {
                
            }
            
            Toolkit.getDefaultToolkit().beep();
           
            setCursor(null); //turn off the wait cursor
           
        }
         
     }
     
     
     
     
     
     
     
     
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
}
